package com.atguigu.gmall.order.listener.mq;

import com.atguigu.gmall.common.util.JSONs;
import com.atguigu.gmall.mq.constant.MqConst;
import com.atguigu.gmall.mq.order.OrderCreateMsg;
import com.atguigu.gmall.mq.service.RabbitMqService;
import com.atguigu.gmall.order.biz.OrderBizService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @author lfy
 * @Description 订单关闭监听器
 * @create 2023-08-04 14:08
 */
@Slf4j
@Service
public class OrderCloseListener {

    @Autowired
    OrderBizService orderBizService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    RabbitMqService mqService;



    @RabbitListener(queues = MqConst.QUEUE_ORDER_DEAD)
    public void closeOrder(Message message, Channel channel){
        //1、提取消息数据
        long deliveryTag = message.getMessageProperties().getDeliveryTag();

        String body =new String(message.getBody());
        //消息整个是唯一的； MD5（不一样的消息，md5一定不一样。）
        OrderCreateMsg msg = JSONs.jsonStr2Obj(body, OrderCreateMsg.class);

        try {

            //2、根据消息处理业务
            log.info("订单关单消息： 订单id：{}，用户id：{}",msg.getOrderId(),msg.getUserId());
            log.info("收到订单关单消息："+msg);
            //处理关单业务
            orderBizService.closeDeadOrder(msg.getOrderId(),msg.getUserId());

            //3、处理成功，手动回复ok
            channel.basicAck(deliveryTag,false);
        }catch (Exception e){
            log.error("订单关闭异常：原因：{}",e);
            try {
                //4、业务处理失败，多次重试
                //关单失败重试 5次
                mqService.retry(body,deliveryTag,channel,5);
            } catch (IOException ex) {
                //说明与MQ断开连接了
                log.error("与MQ断开连接，异常：{}",ex);
            }
        }



    }
}
